package com.tpl.core.basedata.service.impl;

import java.util.List;

import com.tpl.core.basedata.dao.DictMenuDao;
import com.tpl.core.common.exception.RuleException;
import com.tpl.core.common.page.ListPage;
import com.tpl.core.common.page.Page;
import com.tpl.core.dao.ExecuteSql;
import com.tpl.core.entity.sys.DictMenu;
import com.tpl.core.basedata.service.DictMenuService;
import org.springframework.beans.factory.annotation.Autowired;


public class DictMenuServiceImpl implements DictMenuService {
	
	@Autowired
	private DictMenuDao dictMeuDao;
	@Override
	public Page getDictMenus(String key, String kname, int pageIndex, int pageSize) {
		List<DictMenu> list=dictMeuDao.getDictMenuList(key,kname,pageIndex, pageSize);
		int count =dictMeuDao.getDictMenuSelectCount(key,kname);
		return new ListPage(list, pageIndex, pageSize, count);
	}

	@Override
	public DictMenu getDictMenuById(Long dmId) {
		return dictMeuDao.getDictMenuById(dmId);
	}

	@Override
	public void deleteDictMenu(Long dmId) {
		String sql="select count(1) from BD_DATA_DICT_MENU m inner join BD_DATA_DICT d on m.`KEY`=d.`KEY` where d.deleted=0 and m.id=?";
		Long count= ExecuteSql.getSingleResult(Long.class,sql, dmId);
		if(count!=0){
			throw new RuleException("抱歉，该目录已经被引用，请您先删除引用");
		}
		dictMeuDao.deleteDictMenu(dmId);
		
	}

	@Override
	public void saveOrUpdateDictMenu(DictMenu dictMenu) {
		dictMenu.setKey(dictMenu.getKey().replaceAll("\\s",""));
		String sql="select id from BD_DATA_DICT_MENU where `KEY`=? and deleted=0";
		Object id=ExecuteSql.getSingleResult(sql, dictMenu.getKey());
		if(id!=null&&!Long.valueOf(id.toString()).equals(dictMenu.getId()))
			throw new RuleException("抱歉,该字典目录名称已经存在,请重新输入.");
		if(null==dictMenu.getId()){
			dictMenu.setCreateDate(dictMenu.getUpdateDate());
			dictMenu.setCreator(dictMenu.getUpdator());
			dictMeuDao.insertDictMenu(dictMenu);
		}else{
			dictMeuDao.updateDictMenu(dictMenu);
		}
		
	}

	@Override
	public List<DictMenu> getDictMenuList(DictMenu dictMenu) {
		return dictMeuDao.getDictMenuList(dictMenu.getKey(), dictMenu.getName(), 0, 0);
	}

}
